package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    DtsAdminService adminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DtsAdmin admin = (DtsAdmin) principalCollection.getPrimaryPrincipal();
        //角色对应的id
        Integer[] roleIds = admin.getRoleIds();
        //查询角色x
        Set<String> role = roleService.findRolesByRoleIds(roleIds);
        //查询权限
        Set<String> permsByRoleIds = permissionService.findPermsByRoleIds(roleIds);
        //创建返回对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(role);
        simpleAuthorizationInfo.setStringPermissions(permsByRoleIds);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        //根据用户名查找数据库
        DtsAdmin admin = adminService.findByUsername(username);

        if(admin == null) {
            throw new UnknownAccountException("未知的用户");
        }
        if(admin.getDeleted()) {
            throw new LockedAccountException("账户已锁定");
        }
        // 数据库密码，采用的 bcrypt加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(StringUtils.isEmpty(password) || !passwordEncoder.matches(password, admin.getPassword())) {
            throw new CredentialsException("密码错误");
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin, password, username);

        return authenticationInfo;


    }
}
